require 'apr.net'
require 'moonunit'

test_sockets = moonunit.TestCase:new()

function test_sockets:test_client()
    -- Wherever I am, assume I can connect to Google
    local client = apr.net.connect('www.google.com', 80, 10)
    client:write('GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n')
    local page = client:read('*a')
    assert(page:find("I'm Feeling Lucky"))
end

function test_sockets:test_multiformat()
    local client = apr.net.connect('www.google.com', 80, 10);
    client:write('GET / HTTP/1.1\r\n', 'Host: www.google.com\r\n', 'Connection: close\r\n\r\n')
    local line1, line2, rest = client:read('*l', '*l', '*a')
    assert(line1:len() > 0)
    assert(line2:len() > 0)
    assert(rest:find("I'm Feeling Lucky"))
end

function test_sockets:test_server()
    local server = apr.net.create_server(12345, function(client)
        -- a simple line-based echo server
        local line = client:read()
        client:write(line)
    end)
    server:start()
    
    local client = apr.net.connect('localhost', 12345, 10)
    client:write('test request\n')
    server:handle_request()
    assert(client:read() == 'test request')
    client:close()
    server:stop()
end

function test_sockets:test_dnsresolve()
    local addrs = apr.net.dnsresolve('127.0.0.1')
    assert(#addrs == 1)
    assert(addrs[1] == '127.0.0.1')
    
    addrs = apr.net.dnsresolve('www.google.com')
    assert(#addrs >= 1)
    
    addrs = apr.net.dnsresolve('127.0.0.1', true)
    assert(addrs == '127.0.0.1')
end
